<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElRow, ElCol, ElCard, ElButton, ElInput, ElSelect, ElOption, ElPagination, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import http from '../../utils/http'
import { getImageUrl } from '../../utils/system'
import { useRouter } from 'vue-router'
import ProductCard from '../../components/ProductCard.vue'
import useCartStore from '../../stores/cartStore'

const router = useRouter()
const cartStore = useCartStore()

// 商品数据
const productList = ref([])
// 商品分类
const categoryList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 选中的分类
const selectedCategory = ref('')
// 当前页码
const currentPage = ref(1)
// 每页数量
const pageSize = ref(12)
// 总数
const total = ref(0)
// 加载状态
const loading = ref(false)

// 获取商品分类
const getCategoryList = async () => {
  try {
    // 使用虚假数据替代真实API调用
    categoryList.value = [
      { id: 1, name: '传统服饰', description: '传统服饰系列' },
      { id: 2, name: '手工艺品', description: '手工艺品系列' },
      { id: 3, name: '文化用品', description: '文化用品系列' },
      { id: 4, name: '家居装饰', description: '家居装饰系列' },
      { id: 5, name: '艺术收藏', description: '艺术收藏系列' }
    ]
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取商品列表
const getProductList = async () => {
  loading.value = true
  try {
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用虚假数据替代真实API调用
    const mockProducts = [
      {
        id: 1,
        name: '手工刺绣旗袍',
        price: 899.00,
        originalPrice: 1299.00,
        coverImage: '/public/images/手工刺绣旗袍.jpg',
        categoryName: '传统服饰',
        description: '精美手工刺绣旗袍，展现东方女性之美'
      },
      {
        id: 2,
        name: '景泰蓝花瓶',
        price: 599.00,
        originalPrice: 799.00,
        coverImage: '/public/images/景泰蓝花瓶.jpg',
        categoryName: '手工艺品',
        description: '传统景泰蓝工艺制作，色彩艳丽'
      },
      {
        id: 3,
        name: '紫砂茶具套装',
        price: 1299.00,
        originalPrice: 1599.00,
        coverImage: '/public/images/紫砂茶具套装.jpg',
        categoryName: '文化用品',
        description: '宜兴紫砂工艺，泡茶更香醇'
      },
      {
        id: 4,
        name: '木雕屏风',
        price: 2999.00,
        originalPrice: 3999.00,
        coverImage: '/public/images/木雕屏风.jpg',
        categoryName: '家居装饰',
        description: '精工木雕屏风，古典雅致'
      },
      {
        id: 5,
        name: '青花瓷',
        price: 1999.00,
        originalPrice: 2599.00,
        coverImage: '/public/images/青花瓷.jpg',
        categoryName: '艺术收藏',
        description: '珍贵青花瓷器收藏册，极具收藏价值'
      },
      {
        id: 6,
        name: '苏绣团扇',
        price: 299.00,
        originalPrice: 399.00,
        coverImage: '/public/images/苏绣团扇.jpg',
        categoryName: '传统服饰',
        description: '苏州刺绣工艺团扇，精致典雅'
      },
      {
        id: 7,
        name: '陶瓷茶杯套装',
        price: 199.00,
        originalPrice: 299.00,
        coverImage: '/public/images/陶瓷茶杯套装.jpg',
        categoryName: '文化用品',
        description: '景德镇陶瓷工艺，手感温润'
      },
      {
        id: 8,
        name: '竹编收纳篮',
        price: 159.00,
        originalPrice: 199.00,
        coverImage: '/public/images/竹编收纳篮.jpg',
        categoryName: '手工艺品',
        description: '天然竹编工艺，环保实用'
      }
    ]

    // 根据搜索条件过滤数据
    let filteredProducts = [...mockProducts]
    
    // 根据名称过滤
    if (searchKeyword.value) {
      filteredProducts = filteredProducts.filter(product => 
        product.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    }
    
    // 根据分类过滤
    if (selectedCategory.value) {
      filteredProducts = filteredProducts.filter(product => 
        product.categoryName === categoryList.value.find(c => c.id === selectedCategory.value)?.name
      )
    }
    
    // 模拟分页
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    productList.value = filteredProducts.slice(startIndex, endIndex)
    total.value = filteredProducts.length
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1
  getProductList()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  currentPage.value = 1
  getProductList()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  getProductList()
}

// 添加到购物车
const handleAddToCart = async (product) => {
  try {
    // 使用购物车状态管理添加商品
    cartStore.addToCart(product)
    
    ElMessage.success('已添加到购物车')
    console.log('添加到购物车:', product)
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

// 监听分类变化
watch(selectedCategory, () => {
  currentPage.value = 1
  getProductList()
})

// 初始化数据
const initData = async () => {
  await Promise.all([
    getCategoryList(),
    getProductList()
  ])
}

onMounted(() => {
  initData()
})
</script>

<template>
  <div class="shop-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">非遗文创商城</h1>
      <p class="page-subtitle">传承文化，创意生活</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <ElRow :gutter="20" align="middle">
        <ElCol :span="12" :md="8">
          <div class="search-box">
            <ElInput
              v-model="searchKeyword"
              placeholder="请输入商品名称"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <Search class="search-icon" />
              </template>
            </ElInput>
          </div>
        </ElCol>
        <ElCol :span="8" :md="6">
          <ElSelect
            v-model="selectedCategory"
            placeholder="请选择分类"
            clearable
            style="width: 100%"
          >
            <ElOption
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </ElSelect>
        </ElCol>
        <ElCol :span="4" :md="2">
          <ElButton type="primary" @click="handleSearch">搜索</ElButton>
        </ElCol>
        <ElCol :span="4" :md="2">
          <ElButton @click="handleReset">重置</ElButton>
        </ElCol>
        <ElCol :span="4" :md="4" :offset="0">
          <ElButton type="success" @click="$router.push('/front/cart')">
            <i class="el-icon-shopping-cart"></i>
            购物车
          </ElButton>
        </ElCol>
      </ElRow>
    </div>

    <!-- 商品列表 -->
    <div class="products-section">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else>
        <ElRow :gutter="20">
          <ElCol
            v-for="product in productList"
            :key="product.id"
            :span="12"
            :md="6"
            class="product-col"
          >
            <ProductCard 
              :product="product" 
              @add-to-cart="handleAddToCart"
            />
          </ElCol>
        </ElRow>
        
        <!-- 分页 -->
        <div class="pagination-container" v-if="total > pageSize">
          <ElPagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next, jumper"
            @current-change="handlePageChange"
          />
        </div>
        
        <!-- 空状态 -->
        <div v-if="productList.length === 0 && !loading" class="empty-state">
          <div class="empty-icon">
            <i class="el-icon-shopping-bag"></i>
          </div>
          <p class="empty-text">暂无商品数据</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.shop-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 65px - 34px - 32px);
  
  .page-header {
    background: #f7ecec;
    text-align: center;
    margin-bottom: 30px;
    padding: 20px 0;
    
    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: #2c3e50;
      margin-bottom: 10px;
    }
    
    .page-subtitle {
      font-size: 16px;
      color: #7f8c8d;
    }
  }
  
  .search-section {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 30px;
    
    .search-box {
      position: relative;
      
      .search-icon {
        font-size: 16px;
        color: #909399;
      }
    }
  }
  
  .products-section {
    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 50px 0;
      
      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #3498db;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin-bottom: 15px;
      }
      
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      
      p {
        color: #7f8c8d;
      }
    }
    
    .product-col {
      margin-bottom: 20px;
    }
    
    .product-card {
      border-radius: 12px;
      overflow: hidden;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
      }
      
      .product-image-wrapper {
        cursor: pointer;
        height: 200px;
        overflow: hidden;
        background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        
        .product-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;
        }
        
        &:hover .product-image {
          transform: scale(1.05);
        }
      }
      
      .product-info {
        padding: 15px;
        
        .product-name {
          font-size: 16px;
          font-weight: 600;
          color: #2c3e50;
          margin: 0 0 10px 0;
          cursor: pointer;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          
          &:hover {
            color: #3498db;
          }
        }
        
        .product-description {
          font-size: 13px;
          color: #7f8c8d;
          margin: 0 0 15px 0;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .product-price-section {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price-info {
            .current-price {
              font-size: 18px;
              font-weight: 700;
              color: #e74c3c;
            }
            
            .original-price {
              font-size: 13px;
              color: #95a5a6;
              text-decoration: line-through;
              margin-left: 8px;
            }
          }
          
          .add-to-cart-btn {
            padding: 8px 12px;
          }
        }
      }
    }
    
    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 30px;
      padding: 20px 0;
    }
    
    .empty-state {
      text-align: center;
      padding: 50px 0;
      
      .empty-icon {
        font-size: 48px;
        color: #dcdde1;
        margin-bottom: 15px;
      }
      
      .empty-text {
        font-size: 16px;
        color: #7f8c8d;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .shop-container {
    padding: 15px;
    
    .page-header {
      .page-title {
        font-size: 24px;
      }
      
      .page-subtitle {
        font-size: 14px;
      }
    }
    
    .search-section {
      padding: 15px;
      
      :deep(.el-row) {
        flex-direction: column;
        gap: 15px;
      }
      
      :deep(.el-col) {
        width: 100%;
        max-width: 100%;
      }
    }
    
    .products-section {
      .product-card {
        .product-image-wrapper {
          height: 160px;
        }
        
        .product-info {
          padding: 12px;
          
          .product-name {
            font-size: 15px;
          }
          
          .product-description {
            font-size: 12px;
          }
          
          .product-price-section {
            .price-info {
              .current-price {
                font-size: 16px;
              }
              
              .original-price {
                font-size: 12px;
              }
            }
            
            .add-to-cart-btn {
              padding: 6px 10px;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}
</style>